package com.wangxiaonan.inner.controller;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author: wangxiaonan
 * @Date: 2019/3/28
 **/
@Controller
public class IndexController {

    @Resource
    private WebSocketController webSocketController;

    @RequestMapping(value = {"/", "/index", "/index.html"}, method = RequestMethod.GET)
    public String index(@RequestParam(name = "num", defaultValue = "0") String num, Model model) {
        model.addAttribute("num", num);
        return "/index";
    }

    @RequestMapping(value = "/stop", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String stop(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        String username = null;
        for (int i = 0; i < cookies.length; i++) {
            if ("username".equals(cookies[i].getName())) {
                username = cookies[i].getValue();
            }
        }
        if (StringUtils.isEmpty(username)) {
            return "9999";
        }
        webSocketController.senMessage("收到一条消息！", username);
        return "200";
    }
}
